package com.lhy.admin.service;

import com.lhy.admin.common.secure.authorization.Permissions;
import com.lhy.admin.model.Department;
import com.lhy.commonweb.service.AbstractService;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;
import tk.mybatis.mapper.common.Mapper;

import java.util.Date;
import java.util.Optional;

@Service
public class DepartmentService extends AbstractService<Department, Integer> {

    public DepartmentService(@Qualifier("departmentMapper") Mapper<Department> mapper) {
        super(mapper);
    }

    /**
     * @param id
     * @return int
     * @throws
     * @Title: delPermission
     * @Description: 根据部门id 删除部门和子部门
     * @date 2018/6/11 17:14
     */
    @Transactional(rollbackFor = Exception.class)
    public int delDepartment(Integer id) {
        //删除自己
        this.delete(id);
        //删除子权限
        this.deleteCond(new Department().setParent(id));
        return 1;
    }

    public int createDepartment(@RequestBody Department bean) {
        Integer level = Optional.ofNullable(bean.getParent())
                .map(this::get)
                .map(Department::getLevel)
                .map(integer -> integer + 1).orElse(1);
        Date date = new Date();
        Department department = bean.setCreated(date).setUpdated(date).setLevel(level);
        this.add(department);
        Department department1 = new Department().setId(department.getId()).setAncestors(department.getAncestors() + department.getId());
        return this.update(department1);
    }

}
